<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-operator">
        <a-input-search v-model="search" placeholder="输入用户名称" @search="$refs.table.refresh(true)" style="width: 300px; margin-top:10px; margin-right: 20px"/>
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
        <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1"><a-icon type="delete" />删除</a-menu-item>
            <!-- lock | unlock -->
            <a-menu-item key="2"><a-icon type="lock" />锁定</a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px">
            批量操作 <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data="loadData"
        :alert="false"
        :rowSelection="rowSelection"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="description" slot-scope="text">
          <ellipsis :length="50" tooltip>{{ text }}</ellipsis>
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleMenu(record)">岗位</a>
            <a-divider type="vertical" />
            <a @click="handleMenu(record)">用户组</a>
            <a-divider type="vertical" />
            <a @click="handleMenu(record)">菜单</a>
            <a-divider type="vertical" />
            <a @click="handleDel(record)">删除</a>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <step-by-step-modal ref="modal" @ok="handleOk"/>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable, Ellipsis } from '@/components'

import StepByStepModal from '../system/modules/StepByStepModal'
import CreateForm from '../system/group/CreateForm'
import request from '@/utils/request'

const columns = [
  {
    title: '序号',
    width: '100px',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '用户名',
    dataIndex: 'username',
    // sorter: true,
    filters: true
  },
  {
    title: '姓名',
    dataIndex: 'name'
  },
  {
    title: '昵称',
    dataIndex: 'nickname'
  },
  {
    title: '邮箱',
    dataIndex: 'email'
  },
  {
    title: '状态',
    dataIndex: 'enabled',
    sorter: true
  },
  {
    title: '描述',
    dataIndex: 'description'
  },
  {
    title: '更新人',
    dataIndex: 'updatedBy'
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    sorter: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '300px',
    scopedSlots: { customRender: 'action' }
  }
]

function queryData (parameter) {
  return request({
    url: '/alpha-common/users',
    method: 'get',
    params: parameter
  })
}

function postData (parameter) {
  return request({
    url: '/alpha-common/users',
    method: 'post',
    data: parameter
  })
}

function putData (parameter) {
  return request({
    url: '/alpha-common/users/' + parameter['id'],
    method: 'put',
    data: parameter
  })
}

function deleteData (parameter) {
  return request({
    url: '/alpha-common/users/' + parameter['id'],
    method: 'delete',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    },
    data: null
  })
}

export default {
  name: 'UserList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    StepByStepModal
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 查询参数
      search: null,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, { search: this.search })
        console.log('loadData request parameters:', requestParameters)
        return queryData(requestParameters)
          .then(res => {
            return res.result
          })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {
    // methodFilter (type) {
    //   return methodMap[type].text
    // },
    // methodTypeFilter (type) {
    //   return methodMap[type].status
    // }
  },
  created () {
    // getRoleList({ t: new Date() })
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      this.visible = true
      this.mdl = { ...record }
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          if (values.id > 0) {
            // 修改 e.g.
            new Promise((resolve, reject) => {
              setTimeout(() => {
                putData(values)
                resolve()
              }, 1000)
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('修改成功')
            })
          } else {
            // 新增
            new Promise((resolve, reject) => {
              setTimeout(() => {
                postData(values)
                resolve()
              }, 1000)
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('新增成功')
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleMenu (record) {
      new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve()
        }, 1000)
      }).then(res => {
        this.visible = false
        this.confirmLoading = false
      })
    },
    handleDel (record) {
      new Promise((resolve, reject) => {
        setTimeout(() => {
          deleteData(record)
          resolve()
        }, 1000)
      }).then(res => {
        this.visible = false
        this.confirmLoading = false
        // 刷新表格
        this.$refs.table.refresh()

        this.$message.info('删除成功')
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    }
  }
}
</script>
